Option Strict Off
Option Explicit On

Imports System.IO

Friend Class Terminal
    Inherits System.Windows.Forms.Form
    'Public p_Fnum As Short
    Public a_data(136000) As Byte


    'Private Sub cmdDel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdDel.Click
    '		If cmdGrid.Row < cmdGrid.Rows And cmdGrid.Row <> 0 Then
    '			cmdGrid.RemoveItem((cmdGrid.Row))
    '		End If
    '	End Sub
    '
    '    Private Sub cmdGo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGo.Click
    'Dim i As Short
    ' Dim inpStr As String
    '     If cmdGrid.RowSel < cmdGrid.Row Then
    '         i = cmdGrid.Row
    '         cmdGrid.Row = cmdGrid.RowSel
    '         cmdGrid.RowSel = i
    '     End If
    '     For i = 0 To cmdGrid.RowSel - cmdGrid.Row
    '         inpStr = cmdGrid.get_TextArray(cmdGrid.RowSel - i)
    '         sndCmd(inpStr)
    '         Sleep((10))
    '     Next
    ' End Sub

    ' Private Sub cmdGrid_dblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGrid.dblClick
    '   sndCmd((cmdGrid.Text))
    'End Sub

    Private Sub cmdOpenPort_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdOpenPort.Click
        On Error Resume Next
        If usb_connect(Val(uxBaudRateSelector.SelectedItem)) Then
            tmr.Enabled = True
            write_Log("Connected OK! @" & uxBaudRateSelector.SelectedText, "USB")
            ' TxRxGrid.AddItem("USB", 0)
            ' TxRxGrid.set_TextMatrix(0, 1, "Connected OK! @" & Baud.Text)
        Else
            tmr.Enabled = False
            write_Log("Failed to Connect", "USB")
            ' TxRxGrid.AddItem("USB", 0)
            ' TxRxGrid.set_TextMatrix(0, 1, "Failed to Connect")
        End If
    End Sub
    Private Sub cmdSend_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)

        Dim grid As DataGridView = dSent
        If Not IsNothing(dSent.CurrentCell) Then
            sndCmd(grid.CurrentCell.Value)
        End If
    End Sub

    Private Sub Terminal_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        'p_Fnum = FreeFile()
        'FileOpen(p_Fnum, My.Application.Info.DirectoryPath & "\log.txt", OpenMode.Append)
        ' cmdGrid.set_ColWidth(0, 3500)
        ' cmdGrid.set_ColAlignment(0, 0)
        ' TxRxGrid.set_ColWidth(1, 5200)
        ' TxRxGrid.set_ColWidth(0, 1000)
        ' TxRxGrid.set_ColAlignment(1, 0)
    End Sub

    Private Sub Terminal_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        'FileClose(p_Fnum)
        usb_close()
    End Sub
    Private Sub tmr_Tick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles tmr.Tick
        Dim inputStr As String
        Dim inputBytes() As Byte
        Try
            inputBytes = usb_read()

            If Not IsNothing(inputBytes) AndAlso inputBytes.Length > 0 Then
                inputStr = cv_HexFromBytes(inputBytes)
                'TxRxGrid.AddItem("Recv:", 0)
                write_Log(inputStr, Now.Minute & ":" & Now.Second & ":" & Now.Millisecond)
                'WriteLine(p_Fnum, "Recv: " & inputStr)
            End If
        Catch
        End Try
    End Sub

    ' Private Sub TxRxGrid_dblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles TxRxGrid.dblClick
    '    TxRxGrid.Clear()
    'End Sub

    Private Sub txtSend_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtSend.KeyPress
        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
        Dim inputStr As String
        inputStr = txtSend.Text
        If KeyAscii = 13 And inputStr <> "" Then
            sndCmd(inputStr)
            '  If cmdGrid.get_TextArray(0) <> txtSend.Text Then
            'cmdGrid.AddItem(inputStr, 0)
            'End If
            'If Len(inputStr) > 32 Then
            '    cmdGrid.RowHeight(0) = 240 * ((Len(inputStr) \ 32) + 1)
            'Else
            'cmdGrid.set_RowHeight(0, 240)
            'End If
            txtSend.Text = vbNullString
        End If
        eventArgs.KeyChar = Chr(KeyAscii)
        If KeyAscii = 0 Then
            eventArgs.Handled = True
        End If
    End Sub
    Private Sub sndCmd(ByRef str_ As String)
        Dim inp() As Byte
        Dim inputStr As String
        If Len(str_) > 0 Then
            'UPGRADE_WARNING: Couldn't resolve default property of object cv_BytesFromHex(). Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
            inp = cv_BytesFromHex(str_)
            'If Not IsNothing(dSent.CurrentCell) Then
            'If dSent.Item(0, 0).Value <> dSent.CurrentCell.Value Then
            'dSent.RowCount += 1
            'dSent.Item(0, dSent.RowCount - 1).Value = dSent.CurrentCell.Value
            'dSent.FirstDisplayedCell = dGrid.Item(0, dSent.RowCount - 1)
            'End If
            'End If
            If dSent.RowCount > 0 Then
                If dSent.Item(0, dSent.RowCount - 1).Value <> str_ Then
                    dSent.RowCount += 1
                    dSent.Item(0, dSent.RowCount - 1).Value = str_
                    dSent.FirstDisplayedCell = dSent.Item(0, dSent.RowCount - 1)
                End If
            Else
                dSent.RowCount += 1
                dSent.Item(0, 0).Value = str_
                dSent.FirstDisplayedCell = dSent.Item(0, dSent.RowCount - 1)
            End If
            usb_write(inp, UBound(inp) - LBound(inp) + 1)
            inputStr = cv_HexFromBytes(inp)
            'WriteLine(p_Fnum, "Sent: " & inputStr)
            'TxRxGrid.AddItem("Sent:", 0)
            write_Log(inputStr, "Sent:")
        End If
    End Sub
    Public Sub write_Log(ByVal str_ As String, Optional ByVal comment As String = "")
        If Len(str_) > 48 Then
            '    TxRxGrid.set_RowHeight(0, 240 * ((Len(str_) \ 48) + 1))
        Else
            '   TxRxGrid.set_RowHeight(0, 240)
        End If
        'TxRxGrid.AddItem(comment, 0)
        'TxRxGrid.set_TextMatrix(0, 1, str_)
        dGrid.RowCount += 1
        dGrid.Item(1, dGrid.RowCount - 1).Value = str_
        dGrid.Item(0, dGrid.RowCount - 1).Value = comment
        dGrid.FirstDisplayedCell = dGrid.Item(0, dGrid.RowCount - 1)
        If Len(str_) >= 30 Then
            dGrid.CurrentRow.Height = 22 * (Len(str_) \ 30)
        End If
        'Dim boo As Integer
        'boo = dGrid.NewRowIndex()
        ' Err_message(boo)

    End Sub
    Public Sub write_LogBytes(ByRef bytes_() As Byte, ByVal comment As String)
        Dim str_ As String
        If UBound(bytes_) - LBound(bytes_) > 1 Then
            str_ = cv_HexFromBytes(bytes_) & " count: " & UBound(bytes_) - LBound(bytes_)
            If Len(str_) > 48 Then
                ' TxRxGrid.set_RowHeight(0, 240 * ((Len(str_) \ 48) + 1))
            Else
                ' TxRxGrid.set_RowHeight(0, 240)
            End If
            dGrid.RowCount += 1
            dGrid.Item(1, dGrid.RowCount - 1).Value = str_
            dGrid.Item(0, dGrid.RowCount - 1).Value = comment
            dGrid.FirstDisplayedCell = dGrid.Item(0, dGrid.RowCount - 1)
            'TxRxGrid.AddItem(comment, 0)
            'TxRxGrid.set_TextMatrix(0, 1, str_)
        End If

    End Sub

    Private _portOpen As Boolean = False

    Public Property Open As Boolean
        Get
            Return _portOpen
        End Get
        Set(ByVal value As Boolean)
            _portOpen = value
        End Set
    End Property


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cmd() As Byte
        Dim txSnd As String
        txSnd = txSend.Text
        If txSnd <> vbNullString Then
            cmd = cv_BytesFromHex(txSnd)
            SPI_out(cmd(0))
            write_Log(cv_HexFromBytes(cmd), "Send:")
        End If
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim cmd(0) As Byte
        cmd(0) = SPI_in()
        txRcv.Text = cv_HexFromBytes(cmd)
        write_Log(cv_HexFromBytes(cmd), "Recv:")
    End Sub
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        tmr.Enabled = False
        If uxFirmwareViaProg.Checked = True Then
            SPI_Connect(2, "Bikirom USB Propgrammer")
        Else
            SPI_Connect()
        End If

        If spi_reset() Then
            write_Log("SPI Initialised", "SPI:")
        Else
            write_Log("SPI Failed to Initialise", "SPI:")
            write_Log("SPI Disconnected", "SPI:")
            SPI_disconnect()
        End If
    End Sub
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        SPI_disconnect()
        write_Log("SPI Disconnected", "SPI:")
    End Sub
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        If spi_reset() Then
            write_Log("SPI Reset", "SPI:")
        Else
            write_Log("SPI Reset Failed", "SPI:")
        End If
    End Sub
    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        SPI_Monitor()
    End Sub

    Private Sub chRTS_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chRTS.CheckedChanged
        If lngHandle <> 0 Then
            If sender.checked = False Then
                FT_SetRts(lngHandle)
            Else
                FT_ClrRts(lngHandle)
            End If
        End If
    End Sub
    Private Sub chDTR_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chDTR.CheckedChanged
        If lngHandle <> 0 Then
            If sender.checked = False Then
                FT_SetDtr(lngHandle)
            Else
                FT_ClrDtr(lngHandle)
            End If
        End If
    End Sub
    Private Sub bootReset()
        FT_SetRts(lngHandle)
        Threading.Thread.Sleep(20)
        FT_SetDtr(lngHandle)
        Threading.Thread.Sleep(20)
        FT_ClrDtr(lngHandle)
        Threading.Thread.Sleep(20)
    End Sub
    Private Sub bootLoad()
        Threading.Thread.Sleep(20)
        FT_ClrRts(lngHandle)
        Threading.Thread.Sleep(20)
        FT_SetDtr(lngHandle)
        Threading.Thread.Sleep(20)
        FT_ClrDtr(lngHandle)
        Threading.Thread.Sleep(20)
    End Sub

    Private Sub BikiRom_SetTimeoutHigh(ByVal bool As Boolean)
        If bool Then
            FT_SetTimeouts(lngHandle, 10000, 0)
        Else
            FT_SetTimeouts(lngHandle, 2000, 0)
        End If
    End Sub

    Private Function pageCheck(ByVal PageNo As Integer, ByVal m_data() As Byte) As Boolean
        Dim check As Boolean = False
        Dim i As Integer
        For i = PageNo * 256 To PageNo * 256 + 256
            If m_data(i) <> &HFFS Then
                check = True
            End If
        Next
        Return check
    End Function

    Public Function arrayLoad2(ByRef fileName As String) As Byte()
        Dim io As IO.FileStream = Nothing
        Try
            io = New IO.FileStream(fileName, FileMode.Open, FileAccess.Read)
            Dim stream As New IO.BinaryReader(io)

            Dim data As Byte() = stream.ReadBytes(io.Length)

            Return data
        Catch ex As Exception
            Return Nothing
        Finally
            If Not io Is Nothing Then
                io.Close()
            End If
        End Try
    End Function
    Public Function arrayLoad(ByRef fileName As String) As Byte()
        On Error GoTo LoadError
        Dim fnum As Integer
        Dim f_array() As Byte = Nothing


        fnum = FreeFile()
        FileOpen(fnum, fileName, OpenMode.Binary, OpenAccess.Read)
        If LOF(fnum) <> 0 Then
            ReDim f_array(0 To CInt(LOF(fnum) - 1))
            For i As Integer = 1 To CInt(LOF(fnum))
                FileGet(fnum, f_array(i - 1), i)
            Next
        End If
        FileClose(fnum)
        Return f_array
        Exit Function
LoadError:
        Return Nothing
        FileClose(fnum)
    End Function

    Private Sub dataClean(ByRef m_data() As Byte)
        For i As Integer = 0 To UBound(m_data)
            m_data(i) = 255
        Next
    End Sub
    Private Sub dataSet(ByRef m_data() As Byte)
        For i As Integer = LBound(m_data) To UBound(m_data)
            m_data(i) = 0
        Next
    End Sub
    Public Function LOBYTE(ByVal w As Integer) As Byte
        LOBYTE = w And &HFF
    End Function

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        FT_Close(lngHandle)
        lngHandle = 0
        write_Log("USB Disconnected", "USB")
        Me.tmr.Enabled = False
    End Sub

    Private Sub btnErase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnErase.Click
        tmr.Enabled = False
        SPI_Connect()
        spi_reset()
        SPI_out(&HAC)
        SPI_out(&H80)
        SPI_in()
        SPI_in()
        'TxRxGrid.AddItem("SPI:", 0)
        write_Log("Erasing Flash", "SPI:")
    End Sub

    Public Function crc(ByVal cd As Byte, ByRef oldCrc As UShort) As UShort
        Dim i As Integer

        oldCrc = oldCrc Xor cd

        For i = 0 To 7
            If (oldCrc And 1) Then
                oldCrc = (oldCrc \ 2) Xor &HA001
            Else
                oldCrc = (oldCrc \ 2)
            End If
        Next

        Return oldCrc
    End Function

    ''' <summary>
    ''' This function Calculates the CRC of a BikiUSB packet and places it in the CRC location of the frame.
    ''' </summary>
    ''' <param name="Buffer"></param>
    ''' <remarks></remarks>
    Private Sub crcCalculate(ByRef Buffer As Byte())
        Dim i As Integer
        Dim cr As UShort = 0
        For i = 6 To UBound(Buffer) - 4
            cr = crc(Buffer(i), cr)
        Next
        Buffer(UBound(Buffer) - 3) = (cr \ &H100) And &HFF
        Buffer(UBound(Buffer) - 2) = cr And &HFF
    End Sub
    ''' <summary>
    ''' This function Validates the CRC of a BikiUSB packet
    ''' </summary>
    ''' <param name="Buffer"></param>
    ''' <returns>true is a valid packet</returns>
    ''' <remarks></remarks>
    Private Function crcValidate(ByRef Buffer As Byte()) As Boolean
        Dim i As Integer
        Dim cr As UShort = 0
        For i = 6 To UBound(Buffer) - 4
            cr = crc(Buffer(i), cr)
        Next
        If Buffer(UBound(Buffer) - 3) = ((cr \ &H100) And &HFF) And _
           Buffer(UBound(Buffer) - 2) = (cr And &HFF) _
        Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Enum BikiFrameType As Byte
        ID_CONSULT_PASS = &H91
        ID_CONSULT_INTEGRATED = &H92
        ID_FLASH_DATA = &H80
        ID_EEPROM_DATA = &H82
        ID_GENERAL_SPECIFIC = &H55
        ID_LAST_COMMAND_STATUS = &HAA
        ID_RUN_COMMAND = &HE0
        ID_BOOTLOADER = &H70
        ID_ATMEL = &H2A
        ID_PC = &H1A
        ID_ECU = &HA
    End Enum
    Public Enum BikiFrameResponse As Byte
        CMD_OK = &H1
        CMD_FAILED = &H2
        CMD_CRC_FAILED = &H3
        CMD_NEXT = &H4
        SIG_FAILED = &H5
        BUFFER_FULL = &H6
        CMD_INCOMPLETE = &H7
        CMD_UNKNOWN_SENDER = &H8
        CMD_UNKNOWN_RECIVER = &H9
        CMD_UNKNOWN = &H10
        CMD_BAD_HEADS = &HA
        CMD_TIMEOUT = &H1E
        CMD_STOP = &HB
        CMD_GO = &HC
        SEC_BAD_CODE = &H30
        SEC_FUNCTION_LOCKED = &H31
        FLASH_WRITE_TIMEOUT = &H1F
    End Enum
    Public Enum BikiFrameAction As Byte
        WRITE = &H55
        READ = &HAA
        RUN_ERASEALL = &H80
        RUN_ERASESECTOR = &H88
    End Enum

    Private Function frameCreate(ByVal fType As BikiFrameType, Optional ByVal Address As UInt32 = 0, Optional ByVal Action As BikiFrameAction = Nothing, Optional ByVal Payload As Byte() = Nothing) As Byte()
        Dim arrCmd() As Byte = Nothing
        Select Case fType
            Case BikiFrameType.ID_FLASH_DATA
                If Action = BikiFrameAction.WRITE Then
                    ReDim arrCmd(UBound(Payload) + 17)
                    Array.Copy(Payload, 0, arrCmd, 13, Payload.Length)
                ElseIf Action = BikiFrameAction.READ Then
                    ReDim arrCmd(16)
                End If
                If Not IsNothing(arrCmd) Then
                    arrCmd(6) = fType
                    arrCmd(7) = Action
                    arrCmd(8) = (Address \ &H10000) And &HFF
                    arrCmd(9) = (Address \ &H100) And &HFF
                    arrCmd(10) = Address And &HFF
                    arrCmd(11) = (Payload.Length \ &H100) And &HFF
                    arrCmd(12) = Payload.Length And &HFF
                    frameHeadFootCrc(arrCmd)
                End If
            Case BikiFrameType.ID_EEPROM_DATA
            Case BikiFrameType.ID_RUN_COMMAND
                Select Case Action
                    Case BikiFrameAction.RUN_ERASEALL
                        ReDim arrCmd(11)
                    Case BikiFrameAction.RUN_ERASESECTOR
                        ReDim arrCmd(14)
                        arrCmd(8) = (Address \ &H10000) And &HFF
                        arrCmd(9) = (Address \ &H100) And &HFF
                        arrCmd(10) = Address And &HFF
                End Select
                If Not IsNothing(arrCmd) Then
                    arrCmd(6) = fType
                    arrCmd(7) = Action
                    frameHeadFootCrc(arrCmd)
                End If
        End Select
        Return arrCmd
    End Function

    Private Sub frameHeadFootCrc(ByRef frame As Byte())
        If Not IsNothing(frame) AndAlso frame.Length > 6 Then
            frame(0) = &HAA
            frame(1) = &HA5
            frame(2) = &H2A
            frame(3) = &H1A
            frame(4) = ((frame.Length - 10) \ &H100) And &HFF
            frame(5) = (frame.Length - 10) And &HFF
            frame(UBound(frame) - 1) = &H55
            frame(UBound(frame)) = &H5A
            crcCalculate(frame)
        End If
    End Sub

    Private Sub ProgramBlankUSBDevice(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Dim usb_data As New FT_PROGRAM_DATA(0)
        Dim bStatus As Boolean = False
        Dim manu As New String(" ", 40)
        Dim manuid As New String(" ", 40)
        Dim desc As New String(" ", 40)
        Dim serial As New String(" ", 40)
        Dim timeout As Integer

        If BikiRom_connect(, "BikiR0M USB Interface") = BK_return.BK_OK Then
            bStatus = True

            Err_message("Device already programmed")

            close_bikirom()
        ElseIf BikiRom_connect(, "FT232R USB UART") = BK_return.BK_OK OrElse BikiRom_connect(, "USB Serial Converter") = BK_return.BK_OK Then
            bStatus = True

            If bStatus And FT_EraseEE(lngHandle) Then
                bStatus = False
            End If

            If bStatus And FT_EE_ProgramEx(lngHandle, usb_data, usb_data.Manufacturer, usb_data.ManufacturerId, usb_data.Description, usb_data.SerialNumber) Then
                bStatus = False
            End If

            If bStatus And FT_CyclePort(lngHandle) Then
                bStatus = False
            End If

            close_bikirom()

            If bStatus Then
                timeout = 20
                While BikiRom_connect(, "BikiR0M USB Interface") <> BK_return.BK_OK And timeout
                    Threading.Thread.Sleep(1000)
                    timeout -= 1
                End While

                If timeout = 0 Then
                    MsgBox("BikiRom USB Device wait timeout" & Chr(13) & "Wait for device driver to be installed and press OK to continue", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "Device Driver Initialise Timeout")
                End If

                If BikiRom_connect(, "BikiR0M USB Interface") <> BK_return.BK_OK Then
                    bStatus = False
                Else
                    bStatus = True
                    Err_message("New Device Programmed")
                End If

                close_bikirom()
            End If
        End If
    End Sub

    ''' <summary>
    ''' This function automaticaly works out what board you are attempting to program, and auto loads the appropriate firmware files.
    ''' Just trust that this function works... :) This function also loads the base firmware for you.. too easy
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub uxUploadBootloader_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxUploadBootloader.Click
        Dim f_found As Boolean = False
        Dim f As BK_SPEEDS
        Dim f_eepromData As String = Application.StartupPath + "\data\eeprom.bin"
        Dim f_firmware As String = Application.StartupPath & "\data\"
        Dim f_bootloader As String = Application.StartupPath & "\data\"

        ' Firmware files are based upon connection speed..
        Dim speed As Integer = 0
        Select Case uxBaudRateSelector.SelectedItem
            Case "250000"
                speed = 0
            Case "375000"
                speed = 1
            Case "500000"
                speed = 2
        End Select

        Dim dev_name As String = ""
        If uxFirmwareViaProg.Checked = True Then
            dev_name = "BikiR0M USB Interface"
        End If

        Select Case SPI_Connect(, dev_name)
            Case bikirom_target.Unkown
                Err_message("Unable to connect to usb. Insert USB cable and try again")
                Return
            Case bikirom_target.bikiUsb_V2
                Select Case speed
                    Case 0
                        f = BK_SPEEDS.BK_8MHz
                        f_firmware &= "BIKI_OS_1.0.8_2.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_8.bin"
                    Case 1
                        f = BK_SPEEDS.BK_12MHz
                        f_firmware &= "BIKI_OS_1.0.12_2.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_12.bin"
                    Case 2
                        f = BK_SPEEDS.BK_16MHz
                        f_firmware &= "BIKI_OS_1.0.16_2.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_16.bin"
                    Case Else
                        MsgBox("Invalid speed selected")
                        Exit Sub
                End Select
            Case bikirom_target.bikiUsb_V3
                Select Case speed
                    Case 1
                        f = BK_SPEEDS.BK_12MHz_V3
                        f_firmware &= "BIKI_OS_1.0.12_33.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_12_33.bin"
                    Case Else
                        MsgBox("Invalid speed selected for hardware connected")
                        Exit Sub
                End Select
            Case bikirom_target.bikiProgrammer
                Select Case speed
                    Case 1
                        f = BK_SPEEDS.BK_12MHz_V3
                        f_firmware &= "BIKI_OS_1.0.12_33.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_12_33.bin"
                    Case 2
                        f = BK_SPEEDS.BK_16MHz_V3
                        f_firmware &= "BIKI_OS_1.0.16_4.bin"
                        f_bootloader &= "BIKIBOOT_V1.0_16_4.bin"
                    Case Else
                        MsgBox("Invalid speed selected for hardware connected")
                        Exit Sub
                End Select
            Case Else
                MsgBox("Unknown hardware version. Is there a newer programming version?")
                Exit Sub
        End Select

        SPI_disconnect()

        Dim f_firm() As Byte = arrayLoad(f_firmware)
        Dim f_boot() As Byte = arrayLoad(f_bootloader)
        Dim f_EEprom() As Byte = arrayLoad(f_eepromData)

        If IsNothing(f_firm) Or IsNothing(f_boot) Or IsNothing(f_EEprom) Then
            MsgBox("Files Missing")
            Exit Sub
        End If

        Dim serial As String = InputBox("Enter Serial Number", "Serial Number", "000")

        ' Generates some codes for the eeprom..
        If Not Trim(serial) = "" And Val(serial) >= 1 Then
            Dim rand As New Random()
            Dim f_BLoffset As Integer = 3952
            Dim f_EEoffset As Integer = 136
            Dim f_code(15) As Byte
            Dim f_count As Integer = 0
            Dim s As Integer
            For i As Integer = 1 To 8
                rand.NextBytes(f_code)
                f_count = 0
                For Each bit As Byte In f_code
                    f_EEprom(f_EEoffset - (f_count * 8)) = bit
                    f_count += 1
                Next
                f_BLoffset += 16
                f_EEoffset += 1
            Next
            Dim s_num(1) As Byte
            f_EEprom(12) = Val(serial) \ &H10000
            f_EEprom(13) = HIBYTE(Val(serial))
            f_EEprom(14) = LOBYTE(Val(serial))
        End If

        Dim Prog As Program
        If uxFirmwareViaProg.Checked = True Then
            Prog = New Program(f, "Bikirom USB Propgrammer", "BikiR0M USB Interface")
        Else
            Prog = New Program(f)
        End If

        Prog.m_eeprom = f_EEprom
        Prog.m_flash = f_boot
        Prog.m_firmware = f_firm
        bwgProgram.WorkerReportsProgress = True
        bwgProgram.WorkerSupportsCancellation = True
        bwgProgram.RunWorkerAsync(Prog)

        Me.Enabled = False
    End Sub

    Private Sub bwgProgram_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwgProgram.DoWork
        Dim pr As Program = CType(e.Argument, Program)
        AddHandler pr.Message, AddressOf EventProgramProgress
        AddHandler pr.Progress, AddressOf EventProgramProgress

        pr.Execute(bwgProgram, e)
    End Sub
    Private Sub bwgProgram_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwgProgram.ProgressChanged
        Dim state As Emergency_Args = CType(e.UserState, Emergency_Args)
        Me.prog.Value = state.Progress
        Err_message(state.Message)
    End Sub
    Private Sub bwgProgram_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwgProgram.RunWorkerCompleted
        close_bikirom()
        Me.Enabled = True
    End Sub
    Private Sub EventProgramProgress(ByVal sender As Object, ByVal e As Emergency_Args)

        ' A file was found. Report the progress, triggering the
        ' BackgroundWorker.ProgressChanged event:
        Dim intPercent As Integer = e.Progress
        If intPercent >= 100 Then
            intPercent = 100
        ElseIf intPercent < 0 Then
            intPercent = 0
        End If
        bwgProgram.ReportProgress(intPercent, e)
    End Sub

    ''' <summary>
    ''' This function loads your specified firmware file. These are the un-encrypted files from the firmware project. So the straight .bin files will do
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub uxUploadOS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxUploadOS.Click
        upFileOpen.Filter = "Bikirom OS Binary|*.bin"
        upFileOpen.Title = "Select the Bikirom OS .bin file"
        If upFileOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ' Upload the firmware!
            Dim Prog As New Program(BK_SPEEDS.BK_12MHz, , , True)
            Prog.m_eeprom = Nothing
            Prog.m_flash = Nothing
            Dim firm As Byte() = arrayLoad(upFileOpen.FileName)
            Prog.m_firmware = firm
            bwgProgram.WorkerReportsProgress = True
            bwgProgram.WorkerSupportsCancellation = True
            bwgProgram.RunWorkerAsync(Prog)

            Me.Enabled = False
        End If
    End Sub
End Class